<template>
  <div>
    <r-search :searchForm="searchForm" :searchHandle="searchHandle" :searchData="searchData" />
    <r-table :tableHandles="tableHandles" :isSelection="true" :isIndex="false" :isPagination="true"
      :tableData="tableData" :tableCols="tableCols" :tablePage="tablePage" :isHandle="true"
      @select="selectCall" @refresh="init()"></r-table>
    <!--    <r-form :formRules="formRules" :formHandle="formHandle" :formData="formData" :formCols="formCols" ref="elForm" labelWidth="200px" dialogWidth="1000px" :isHandle="true" />-->

    <r-form labelWidth="150px" :isHandle="true" :formRules="formRules2" :formCols="formCols2"
      :formHandle="formHandle2" :formData="formData2" ref="elForm2" :inline="false"
      dialogWidth="850px">
      <div slot="slot3">
        <div id="searchResultPanel"
          style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
        <p>点击地图拾取坐标 经度：{{ formData2.lng }} 纬度：{{ formData2.lat }}</p>
        <div id="l-map"></div>
      </div>
    </r-form>

    <!--    <add_device v-if="add_device_data.show" v-on:add_device_call="add_device_call"></add_device>-->
    <!--    <warehouse_gate :res="warehouse_gate_data" v-if="warehouse_gate_data.show" v-on:warehouse_gate_dall="warehouse_gate_dall"></warehouse_gate>-->
    <related_packages ref="related_packages"></related_packages>
  </div>
</template>
<script>
// import add_device from "./cus/add_device";
// import warehouse_gate from "./cus/warehouse_gate";
import related_packages from './cus/related_packages'
import baidumap from '../js/baidumap'
export default {
  components: {
    // add_device,
    // warehouse_gate,
    related_packages
  },
  data() {
    return {
      baiduMap: null,
      add_device_data: {
        show: false
      },
      warehouse_gate_data: {
        id: '',
        show: false
      },
      searchData: {
        deviceName: '',
        sn: '',
        deviceStatus: '',
        operatorId: '',
        agentId: '',
        distStatus: '',
        commonType: '',
        deviceType: 2
      },
      searchForm: [
        {
          type: 'input',
          prop: 'sn',
          placeholder: '设备编号',
          width: 150
        },
        {
          type: 'input',
          prop: 'deviceName',
          placeholder: '设备名称',
          width: 150
        },
        {
          type: 'select',
          prop: 'operatorId',
          placeholder: '所属运营商',
          width: 150
        },
        {
          type: 'select',
          prop: 'agentId',
          placeholder: '所属代理商',
          width: 150
        },
        {
          type: 'select',
          prop: 'distStatus',
          placeholder: '是否分配',
          width: 150,
          options: [{ label: '未分发', value: '0' }, { label: '已分发', value: '1' }]
        },
        {
          type: 'select',
          prop: 'commonType',
          placeholder: '公有类型',
          width: 150,
          options: [{ label: '公有', value: '1' }, { label: '私有', value: '2' }]
        }
        // {
        //   type: 'select',
        //   prop: 'name',
        //   placeholder: '设备类型',
        //   width: 150,
        //   options:[
        //     {label:'换电柜',value:'1'},
        //     {label:'租车',value:'2'},
        //     {label:'充电柜',value:'3'},
        //   ]
        // },
      ],
      searchHandle: [
        {
          label: '搜索',
          type: 'success',
          icon: 'el-icon-search',
          handle: e => this.init()
        }
      ],

      tableHandles: [
        // {
        //   label: "关联广告合集",
        //   type: "primary",
        //   handle: e => this.elFormVisible()
        // },
        {
          label: '关联套餐',
          type: 'primary',
          handle: e => {
            if (this.deviceId.length == 0) {
              return this.$message({
                message: '请选择设备！',
                type: 'error'
              })
            }
            this.$refs.related_packages.showFun(this.deviceId)
          }
        },
        {
          label: '添加设备',
          type: 'primary',
          handle: e => {
            this.add()
          }
        }
        // {
        //   label: "下载模板",
        //   type: "primary",
        //   handle:async () => {
        //     const res=await this.apis.importTemplate();
        //
        //     location.href=process.env.VUE_APP_URL+res.msg;
        //
        //   }
        // }
      ],
      tableData: [],
      tableCols: [
        {
          label: '设备编号',
          prop: 'sn'
        },
        {
          label: '二维码',
          type: 'image',
          width: 100,
          prop: 'qrCode'
        },
        {
          label: '设备名称',
          prop: 'deviceName'
        },
        {
          label: '铺设站点',
          prop: 'siteId'
        },
        {
          label: '当前定位',
          prop: 'lng',
          formatter: row => {
            if (row.lng) {
              return row.lng + ',' + row.lat
            } else {
              return '-'
            }
          }
        },
        /* {
          label: '充电柜套餐',
          prop: 'mealId'
        }, */
        {
          label: '设备所属',
          prop: 'operatorName'
        },
        {
          label: '运维人员',
          prop: 'merName'
        },
        // {
        //   label: '广告合集',
        //   prop: 'giftMoney'
        // },
        {
          label: '电量表',
          prop: 'usedElectric'
        },
        {
          label: '设备状态',
          prop: 'deviceStatus',
          formatter: e => {
            if (e.deviceStatus == 1) {
              return '(在线)运行中'
            } else if (e.deviceStatus == 2) {
              return '离线'
            } else if (e.deviceStatus == 3) {
              return '设备故障'
            } else if (e.deviceStatus == 0) {
              return '-'
            }
          }
        },
        /* {
          label: '更新时间',
          prop: 'lastTime'
        }, */
        {
          label: '启用状态',
          type: 'switch',
          prop: 'useStatus',
          values: [1, 2],
          change: row => this.changestate(row)
        },
        {
          label: '操作',
          type: 'button',
          width: 300,
          btnList: [
            {
              label: '编辑',
              type: 'text',
              handle: row => {
                this.add(row)
              }
            },
            {
              label: '删除',
              type: 'text',
              handle: async row => {
                this.$confirm('确定要删除吗?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                })
                  .then(async () => {
                    var res = await this.apis.device_del({
                      id: row.id
                    })
                    this.$message({
                      type: 'success',
                      message: '删除成功!'
                    })
                    this.init()
                  })
                  .catch(() => { })
              }
            }
          ]
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 },
      // formData: {
      //   name: "",
      //   money: "",
      //   giftMoney: "",
      //   status: ""
      // },
      // formCols: [
      //   { type: "input", label: "套餐名称", width: 350, prop: "name" },
      //   { type: "input", label: "套餐金额", width: 350, prop: "money", remark: '元' },
      //   { type: "input", label: "赠送金额", width: 350, prop: "giftMoney", remark: '元' },
      //   { type: "switch", label: "上线/下线", width: 350, prop: "status" },
      // ],
      // formRules: {
      //   name: [
      //     { required: true, message: '请输入套餐名称', trigger: 'blur' },
      //   ],
      //   money: [
      //     { required: true, message: '请输入套餐金额', trigger: 'blur' },
      //   ],
      //   giftMoney: [
      //     { required: true, message: '请输入套餐金额', trigger: 'blur' },
      //   ],
      // },
      // formHandle: [
      //   {
      //     label: "取消",
      //     handle: e => this.elFormVisible(),
      //   },
      //   {
      //     label: "确定",
      //     type: "success",
      //     handle: e => this.elFormSubmit(),
      //   },
      //
      // ],

      formData2: {
        deviceNo: '',
        deviceName: '',
        address: '',
        siteId: '',
        lng: '',
        lat: '',
        operatorId: '',
        agentId: '',
        merId: '',
        boxNum: '',
        sim: '',
        deviceType: '2',
        mealId: '',
        carDeposit: '',
        btType: ''
      },
      formCols2: [
        { type: 'input', label: '设备编号', placeholder: '请输入', width: 350, prop: 'deviceNo' },
        { type: 'input', label: '设备名称', placeholder: '请输入', width: 350, prop: 'deviceName' },
        {
          type: 'select',
          label: '电池类型',
          placeholder: '请输入',
          width: 350,
          prop: 'btType',
          options: [{ label: '48V', value: 48 }, { label: '60V', value: 60 }, { label: '72V', value: 72 }]
        },
        // { type: "input", label: "格子数量", placeholder: '请输入', width: 350, prop: "boxNum", },
        // { type: "input", label: "sim 编号", placeholder: '请输入', width: 350, prop: "sim", },
        // { type: "select", label: "设备类型", placeholder: '请输入', width: 350, prop: "deviceType",options:[
        //     {label:'换电柜',value:'1'},
        //     {label:'租车',value:'2'},
        //     {label:'充电柜',value:'3'},
        //   ] },
        { type: 'select', label: '选择站点', placeholder: '请输入', width: 350, prop: 'siteId', options: [] },
        { type: 'select', label: '选择运营商', placeholder: '请输入', width: 350, prop: 'operatorId', options: [] },
        { type: 'select', label: '选择代理商', placeholder: '请输入', width: 350, prop: 'agentId', options: [] },
        { type: 'select', label: '选择运维', placeholder: '请输入', width: 350, prop: 'merId', options: [] },
        { type: 'input', label: '车辆押金', placeholder: '请输入', width: 350, prop: 'carDeposit', remark: '元' }
        // { type: "select", label: "关联套餐",placeholder:'请输入', width: 350, prop: "mealId" },
        // { type: "input", id: 'suggestId', label: "站点地址", width: 350, prop: "address" },
        // { type: "slot", name: 'slot3', label: '', prop: "lng" },
      ],
      formRules2: {
        deviceNo: [{ required: true, message: '请输入', trigger: 'blur' }],
        deviceName: [{ required: true, message: '请输入', trigger: 'blur' }],
        btType: [{ required: true, message: '请选择', trigger: 'blur' }],
        boxNum: [{ required: true, message: '请输入', trigger: 'blur' }],
        sim: [{ required: true, message: '请输入', trigger: 'blur' }],
        deviceType: [{ required: true, message: '请选择', trigger: 'blur' }],
        siteId: [{ required: true, message: '请选择', trigger: 'blur' }],
        operatorId: [{ required: true, message: '请选择', trigger: 'blur' }],
        agentId: [{ required: true, message: '请选择', trigger: 'blur' }],
        merId: [{ required: true, message: '请选择', trigger: 'blur' }],
        lng: [{ required: true, message: '请点击地图选择经纬度', trigger: 'blur' }],
        address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        carDeposit: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      formHandle2: [
        {
          label: '取消',
          handle: e => this.elFormVisible('', 'elForm2')
        },
        {
          label: '确定',
          type: 'success',
          handle: e => this.elFormSubmit()
        }
      ],

      deviceId: []
    }
  },
  computed: {},
  mounted() {
    this.init()
    this.site_list()
    this.operator_list()
    this.agent_list()
    this.maintenancer_list()
    this.mealExchange_list()
  },
  methods: {
    async init() {
      let parm = {
        ...this.searchData,
        ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit
        }
      }
      let res = await this.apis.device_list(parm)
      if (res) {
        this.tableData = res.rows
        this.tablePage.total = res.total
      }
    },
    async elFormSubmit() {
      this.$refs.elForm2.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.formData2.id) {
            let res = await this.apis.device_updata(this.formData2)
            if (res) {
              this.init()
              this.elFormVisible('', 'elForm2')
            }
          } else {
            let res = await this.apis.device_save(this.formData2)
            if (res) {
              this.init()
              this.elFormVisible('', 'elForm2')
            }
          }
        }
      })
    },
    async changestate(row) {
      let res = await this.apis.device_updata({
        id: row.id,
        useStatus: row.useStatus
      })

      this.$message({
        message: '操作成功！',
        type: 'success'
      })
    },
    elFormDetail(row) {
      console.log(row)
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key]
      })

      this.formData.status = row['state'] == 1 ? true : false
      this.formData.id = row.id
      // if (this.formCols[1].label == '登录密码') {
      //     this.formCols.splice(1, 1)
      // }

      this.elFormVisible()
    },
    map() {
      var that = this
      var map = baidumap(that)
      this.baiduMap = map
      var geoc = new BMap.Geocoder()
      map.addEventListener('click', function (e) {
        that.formData2.lng = e.point.lng
        that.formData2.lat = e.point.lat
        var pt = e.point
        geoc.getLocation(pt, function (rs) {
          var addComp = rs.addressComponents
          that.formData.city = addComp.city
          // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
        })
      })
      map.enableScrollWheelZoom() //启用滚轮放大缩小，默认禁用
      map.enableContinuousZoom() //启用地图惯性拖拽，默认禁用
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, 10)
      })
    },
    add(row) {
      if (row) {
        this.formData2.id = row.id
      } else {
        this.formData2.id = ''
      }
      this.elFormVisible('', 'elForm2').then(res => {
        if (row) {
          Object.keys(this.formData2).forEach(key => {
            this.formData2[key] = row[key]
          })
        }
      })
    },
    //站点列表
    async site_list() {
      const res = await this.apis.site_list({
        pageNum: 1,
        pageSize: 100000
      })

      const list = res.rows || []
      let options = []
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        })
      })

      this.formCols2[this.labIndex2(this.formCols2, 'siteId')].options = options
    },

    //运营商-列表
    async operator_list() {
      const res = await this.apis.operator_list({
        pageNum: 1,
        pageSize: 100000
      })
      const list = res.rows || []
      let options = []
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        })
      })

      this.formCols2[this.labIndex2(this.formCols2, 'operatorId')].options = options
    },
    //代理商列表
    async agent_list() {
      const res = await this.apis.agent_list({
        pageNum: 1,
        pageSize: 100000
      })
      const list = res.rows || []
      let options = []
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        })
      })

      this.formCols2[this.labIndex2(this.formCols2, 'agentId')].options = options
    },
    //运维员列表
    async maintenancer_list() {
      const res = await this.apis.maintenancer_list({
        pageNum: 1,
        pageSize: 1000000,
        status: 1
      })
      const list = res.rows || []
      let options = []
      list.map(res => {
        options.push({
          label: res.userName,
          value: res.id
        })
      })

      this.formCols2[this.labIndex2(this.formCols2, 'merId')].options = options
    },

    //套餐列表
    async mealExchange_list() {
      const res = await this.apis.mealExchange_list({
        pageNum: 1,
        pageSize: 1000000
      })
      const list = res.rows || []
      let options = []
      list.map(res => {
        options.push({
          label: res.mealName,
          value: res.id
        })
      })
      // this.formCols2[this.labIndex2(this.formCols2, 'mealId')].options = options;
    },
    // warehouse_gate_dall(){
    //   this.warehouse_gate_data.show=false;
    // },
    selectCall(rows) {
      console.log(rows)
      this.deviceId = []
      let deviceId = []
      rows.map(res => {
        deviceId.push(res.id)
      })
      this.deviceId = deviceId
    }
  }
}
</script>
<style scoped lang="scss">
.el-icon-search {
  margin-right: 10px;
}
.Tip {
  margin-left: 20px;
}

#l-map {
  height: 250px;
  width: 100%;
}
#r-result {
  width: 100%;
}
</style>
